package com.example.vv.model.login.base.presenter;

import android.util.Log;

import com.example.vv.frameWork.entity.LoginEntity;
import com.example.vv.frameWork.mvp.MvpPresenter;

import com.example.vv.frameWork.mvp.ViewISNullException;
import com.example.vv.model.login.base.contract.LoginContract;
import com.example.vv.model.login.base.model.LoginModel;
import com.example.vv.req.REQ_LOGIN;
import com.example.vv.res.BaseRespont;
import com.google.gson.Gson;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class LoginPresenter extends MvpPresenter<LoginContract.View, LoginContract.Model> implements LoginContract.Presenter {
    @Override
    public void attach(LoginContract.View view) {
        super.attach(view);
        model=new LoginModel();
    }

    @Override
    public void login() {
        try {
            REQ_LOGIN re = new REQ_LOGIN(view().getPhone(), view().getUserPassWord());
            model.login(re)
                    .map(new Function<BaseRespont, LoginEntity>() {
                        @Override
                        public LoginEntity apply(BaseRespont baseRespont) {
                            return new Gson().fromJson(baseRespont.getBaseData(),LoginEntity.class);
                        }
                    }).subscribe(new Consumer<LoginEntity>() {
                @Override
                public void accept(LoginEntity loginEntity) {
                    try {
                        view().setLoginEntity(loginEntity);
                        Log.e("sdfasfsadf",  loginEntity.getMessage());
                    } catch (ViewISNullException e) {
                        e.printStackTrace();
                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {

                }
            });
        } catch (ViewISNullException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean isFormat() {
        try {
            return view().getPhone()!=null&&view().getPhone().length()==11&&view().getUserPassWord().length()>6;
        } catch (ViewISNullException e) {
            e.printStackTrace();
            return false;
        }
    }
}
